import React, { useEffect, useState } from "react";
import "./recentevents.css";
import axios from "axios";

export default function Recentevents() {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [direction, setDirection] = useState("next");

  const [events, setEvents] = useState([]);

  const init = async () => {
    const response = await axios.get("http://192.168.0.154:3000/my/rili");
    setEvents(response.data);
  };

  useEffect(() => {
    init();
  }, []);

  const handlePrev = () => {
    setDirection("prev");
    setCurrentIndex((prev) => (prev === 0 ? events.length - 1 : prev - 1));
  };

  const handleNext = () => {
    setDirection("next");
    setCurrentIndex((prev) => (prev === events.length - 1 ? 0 : prev + 1));
  };
  return (
    <div className="events-container">
      <button className="nav-button prev" onClick={handlePrev}>
        <span>←</span>
      </button>
      <div className="events-wrapper">
        {events.map((event, index) => (
          <div
            key={event.id}
            className={`event-card ${index === currentIndex ? "active" : ""} ${
              direction === "next" ? "slide-next" : "slide-prev"
            }`}
            style={{
              transform: `translateX(${(index - currentIndex) * 100}%)`,
              opacity: index === currentIndex ? 1 : 0,
            }}
          >
            <div className="event-content">
              <div className="event-title">
                {event.title}
                <div className={`direction-arrow ${event.direction}`}>
                  {event.direction === "up" ? "↑" : "↓"}
                </div>
              </div>
              <div className="event-time">
                <span className="time">{event.time}</span>
                <div className="duration">
                  <span className="clock-icon">🕐</span>
                  {event.duration}
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
      <button className="nav-button next" onClick={handleNext}>
        <span>→</span>
      </button>
    </div>
  );
}
